package codedown


import (
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"regexp"
	"strings"
)

var IsShowDebug bool = false

func getUrl(url string) string {
	resp,err := http.Get(url)
	if err != nil {
		fmt.Println(err)
		return ""
	}
	defer resp.Body.Close()
	var buff = make([]byte, 1024 * 4)
	var result string
	for {
		n,err := resp.Body.Read(buff)
		if n == 0 {
			if IsShowDebug {
				fmt.Println("read data err", err)
			}
			break
		}
		result += string(buff[:n])
	}
	return result
}

func resolve(content string) []string {
	re,_ := regexp.Compile("\\<a\\s+href=['\"]?(.*?)['\"]?\\s*(([^&]>)|(\\/\\>))")
	res := re.FindAllSubmatch([]byte(content), -1)
	var list = make([]string, len(res))
	for i:=0; i < len(res); i ++ {
		for j:=0;j<len(res[i]);j++ {
			if IsShowDebug {
				println(string(res[i][j]))
			}
			if j == 1 { // href="xxxx"
				list[i] = string(res[i][j])
				break
			}
		}
	}
	return list
}

func download(url, fileName string)  {
	resp,err := http.Get(url)
	if err != nil {
		fmt.Println("download",url,"save to",fileName,"failure:",err)
		return
	}
	defer resp.Body.Close()
	buff,err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("download data err:",err)
		return
	}
	file,err:= os.Create(fileName)
	if err != nil {
		fmt.Println("create file",fileName,"error:",err)
		return
	}
	file.Write(buff)
	file.Close()
	fmt.Println("save",url,"to",fileName)
}

func Run(url,root string)  {
	content := getUrl(url)
	if IsShowDebug {
		println(content)
	}
	paths := resolve(content)
	if IsShowDebug {
		println("=========================")
		fmt.Println(paths)
	}
	for _,path := range paths {
		if strings.Index(path,"..") > -1 { // 回上一级
			continue
		}
		if !strings.HasSuffix(path, "/") {
			download(url+path,root+path)
			continue
		}
		p := root + path
		if !isExists(p){
			os.MkdirAll(p, os.ModeDir)
		}
		Run(url+path, root+path)
	}
}

func isExists(dir string) bool {
	fi,err := os.Stat(dir)
	if err != nil {
		return false
	}
	return fi.IsDir()
}

func main2() {
	url := "http://www.oldlinux.org/Book-Lite/linux-0.12/"
	content := getUrl(url)
	println(content)
	paths := resolve(content)
	println("xxxxxxxxxxx")
	root := "download/"
	fmt.Println(paths)
	for _,path := range paths {
		if strings.Index(path,".") > -1 || !strings.HasSuffix(path, "/") {
			continue
		}
		p := root + path
		if isExists(p){
			continue
		}
		os.MkdirAll(p, os.ModeDir)
	}
}
